package com.scfire.security

import org.apache.commons.lang.builder.HashCodeBuilder

/**
 * Copyright 2015 Shudao Info Tech Co. Ltd.  All rights reserved.
 * @author lhzeng
 * @email zenglh@haoshudao.com
 * @date 2015年6月7日 下午1:25:20
 * @version V1.0
 */

class MemberAuthority implements Serializable {

	private static final long serialVersionUID = 1

	Member member
	Authority authority

	boolean equals(other) {
		if (!(other instanceof MemberAuthority)) {
			return false
		}

		other.member?.id == member?.id &&
		other.authority?.id == authority?.id
	}

	int hashCode() {
		def builder = new HashCodeBuilder()
		if (member) builder.append(member.id)
		if (authority) builder.append(authority.id)
		builder.toHashCode()
	}

	static MemberAuthority get(long memberId, long authorityId) {
		MemberAuthority.where {
			member == Member.load(memberId) &&
			authority == Authority.load(authorityId)
		}.get()
	}

	static boolean exists(long memberId, long authorityId) {
		MemberAuthority.where {
			member == Member.load(memberId) &&
			authority == Authority.load(authorityId)
		}.count() > 0
	}

	static MemberAuthority create(Member member, Authority authority, boolean flush = false) {
		def instance = new MemberAuthority(member: member, authority: authority)
		instance.save(flush: flush, insert: true)
		instance
	}

	static boolean remove(Member u, Authority r, boolean flush = false) {
		if (u == null || r == null) return false

		int rowCount = MemberAuthority.where {
			member == Member.load(u.id) &&
			authority == Authority.load(r.id)
		}.deleteAll()

		if (flush) { MemberAuthority.withSession { it.flush() } }

		rowCount > 0
	}

	static void removeAll(Member u, boolean flush = false) {
		if (u == null) return

		MemberAuthority.where {
			member == Member.load(u.id)
		}.deleteAll()

		if (flush) { MemberAuthority.withSession { it.flush() } }
	}

	static void removeAll(Authority r, boolean flush = false) {
		if (r == null) return

		MemberAuthority.where {
			authority == Authority.load(r.id)
		}.deleteAll()

		if (flush) { MemberAuthority.withSession { it.flush() } }
	}

	static constraints = {
		authority validator: { Authority r, MemberAuthority ur ->
			if (ur.member == null) return
			boolean existing = false
			MemberAuthority.withNewSession {
				existing = MemberAuthority.exists(ur.member.id, r.id)
			}
			if (existing) {
				return 'userRole.exists'
			}
		}
	}

	static mapping = {
		id composite: ['authority', 'member']
		version false
	}
}
